import logging
import os

import numpy as np
import pandas as pd

from opt import Opt

__all__ = ["find", "printret"]


def listfile(d: str) -> []:
    files = []
    for path, dir_list, file_list in os.walk(d):
        logging.debug("path:{}".format(path))
        for dir_name in dir_list:
            files = files + listfile(os.path.join(path, dir_name))

        for f in file_list:
            files.append(os.path.join(path, f))

    return files


class findret:
    def __init__(self, fn: str, sn: str):
        self.fn = fn
        self.sn = sn

    def __str__(self):
        return "file:{},sheet:{}".format(self.fn, self.sn)


def printret(ret: []):
    for r in ret:
        logging.info(r)


def find(o: Opt) -> []:
    logging.info(o)
    files = listfile(o.dir)
    ret = []
    for f in files:
        e = pd.read_excel(io=f, sheet_name=None, header=o.field.row, index_col=None, dtype=str)
        for sn in e:
            if o.sheetName != "":
                if o.sheetName == sn:
                    ret.append(findret(f, sn))
                continue

            d = e[sn]
            if o.field.name != "":
                if o.field.name not in d:
                    continue
                w = np.where(d[o.field.name] == o.content)
            else:
                w = np.where(d == o.content)

            if len(w) > 0 and w[0].size > 0:
                ret.append(findret(f, sn))
                break

    return ret
